package com.campus.delivery.listener;

import com.campus.common.message.MealReadyMessage;
import com.campus.delivery.service.WebSocketService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 出餐消息Kafka监听器
 * 监听商户端发送的出餐消息，并推送给配送员
 */
@Component
@Slf4j
public class MealReadyKafkaListener {

    @Autowired
    private WebSocketService webSocketService;
    
    @Resource
    private ObjectMapper objectMapper;


    /**
     * 监听出餐消息
     * 
     * @param message 出餐消息JSON字符串
     */
    @KafkaListener(topics = "meal-ready", groupId = "delivery-group")
    public void handleMealReadyMessage(String message) {
        try {
            log.info("收到出餐消息: {}", message);
            
            // 解析JSON消息
            MealReadyMessage mealReadyMessage = objectMapper.readValue(message, MealReadyMessage.class);
            
            Integer deliveryId = mealReadyMessage.getDeliveryId();

            if (deliveryId == null) {
                log.warn("订单未分配配送员，订单ID: {}", mealReadyMessage.getOrderId());
                return;
            }

            String notificationContent = "订单" + mealReadyMessage.getOrderId() + "已出餐，请及时取餐配送！";
            
            // 只推送给指定的配送员
            webSocketService.sendMealReadyNotification(deliveryId, notificationContent);
            
            log.info("出餐消息推送成功，订单ID: {}, 配送员ID: {}",
                    mealReadyMessage.getOrderId(), deliveryId);
            
        } catch (Exception e) {
            log.error("处理出餐消息失败: {}", e.getMessage(), e);
        }
    }
}